package com.example.campuslink.ui.activity.search

import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.campuslink.BR
import com.example.campuslink.R
import com.example.campuslink.commen.adpter.HotSearchAdapter
import com.example.campuslink.commen.adpter.SearchHistoryAdapter
import com.example.campuslink.commen.tools.SpacesItemButtonDecoration
import com.example.campuslink.databinding.ActivitySearchMainBinding
import com.example.campuslink.ui.activity.BaseActivity
import com.example.campuslink.viewModel.search.SearchMainViewModel

class SearchMainActivity : BaseActivity<ActivitySearchMainBinding, SearchMainViewModel>(
    SearchMainViewModel::class.java,
    R.layout.activity_search_main,
    BR.viewModel
) {
    private var searchHistoryAdapter: SearchHistoryAdapter? = null
    private var hotSearchAdapter: HotSearchAdapter? = null

    override fun onRestart() {
        super.onRestart()
        mViewModel?.getAllSchoolSearch()
        mViewModel?.getSearchInfo()
    }

    override fun initView() {
        initData()
        mViewModel?.searchInfo?.observe(this) {
            searchHistoryAdapter?.setListData(it?.reversed() ?: mutableListOf())
        }
        mViewModel?.schoolSearch?.observe(this) { it ->
            it?.sortWith(compareByDescending { it.searchCount })
            hotSearchAdapter?.setListData(it ?: mutableListOf())
        }
        mViewDataBinding?.rvHistory?.adapter = searchHistoryAdapter
        mViewDataBinding?.rvHistory?.layoutManager = GridLayoutManager(this, 4)
        mViewDataBinding?.rvHot?.adapter = hotSearchAdapter
        mViewDataBinding?.rvHot?.layoutManager = LinearLayoutManager(this)
        mViewDataBinding?.rvHot?.addItemDecoration(SpacesItemButtonDecoration(20))
        mViewDataBinding?.ivBack?.setOnClickListener {
            finish()
        }
        mViewDataBinding?.tvSearch?.setOnClickListener({
            mViewModel?.addSearchInfo(mViewDataBinding?.etSearchContent?.text.toString())
            mViewModel?.jumpToSearchResult(mViewDataBinding?.etSearchContent?.text.toString())
        })

    }

    private fun initData() {
        mViewModel?.context = this
        mViewModel?.initDB(this)
        searchHistoryAdapter = SearchHistoryAdapter(mViewModel!!)
        hotSearchAdapter = HotSearchAdapter(mViewModel!!)
        mViewModel?.getAllSchoolSearch()
        mViewModel?.getSearchInfo()

    }
}